<template>
  <div class="components-input-demo-presuffix">
    <!---->
    <a-input @click="openModal" :placeholder="placeholder || $t('m.common.label.option_select')" v-model="names" readOnly :disabled="disabled">
      <ych-icon slot="prefix" type="appstore" :title="$t('m.common.label.option_select')"/>
      <ych-icon v-if="value && !disabled" slot="suffix" type="close-circle" @click="handleEmpty" :title="$t('m.common.button.clear')"/>
    </a-input>

    <view-select-modal
      ref="modal"
      :multi="multi"
      :viewCode="viewCode"
      :rows="rows"
      :keys="keys"
      :stores="stores"
      :labelField="labelField"
      @ok="handleOK"/>
  </div>
</template>

<script>

  import { postAction } from '@/api/manage'
  import ViewSelectModal from './ViewSelectModal'
  import YchConstant from "@/api/YchConstant";

  export default {
    name: 'ViewSelectTag',
    components: {
      ViewSelectModal
    },
    props: {
      placeholder: {
        type: String,
      },
      viewCode: {
        type: String,
        default: null
      },
      multi: {
        type: Boolean,
        default: false,
        required: false
      },
      value: {
        type: String,
        required: false
      },
      disabled: {
        type: Boolean,
        required: false,
        default: false
      },
      keyField: {
        type: String,
        default: null
      },
      labelField: {
        type: String,
        default: null
      },
      fields: {
        type: Array,
        default: () => []
      },
      parameterConfig: {
        type: Array,
        default: () => []
      },
      form: {
        type: Object,
        default: () => {
        }
      },
      record: {
        type: Object,
        default: () => {
        }
      },
      stores: {
        type: Object,
        default: () => {
          return {}
        }
      }
    },
    data () {
      return {
        names: '',
        url: {
          queryViewListByIds: YchConstant.PREFIX_EFORM + '/engine/viewEngine/queryViewListByIds',
        },
        rows: [],
        keys: [],
      }
    },
    watch: {
      value: {
        handler () {
          this.initNames()
        },
        immediate: true
      },
    },
    methods: {
      initNames () {
        if (!this.labelField) {
          //显示字段不存在
          return
        }
        if (!this.keyField || this.keyField == this.labelField) {
          //只有显示字段存在或存储与显示一致，TODO id
          this.rows = []
          this.keys = []
          this.names = this.value

          this.$emit("setName", this.names)
          return
        }
        if (!this.viewCode) {
          return
        }
        if (this.value && this.value.length > 0) {
          const url = this.url.queryViewListByIds + '?viewCode=' + this.viewCode
          postAction(url, {
            queryValue: [{
              colCode: this.keyField,
              queryValue: this.value
            }]
          }).then((res) => {
            if (res.success) {
              this.rows = res.result
              this.keys = this.rows.map(row => row['id'])
              this.names = this.rows.map(row => row[this.labelField]).join(',')
            } else {
              this.rows = []
              this.keys = []
              this.names = ''
              this.messageUtil.warning(res.message)
            }

            this.$emit("setName", this.names)
          })
        } else {
          this.rows = []
          this.keys = []
          this.names = ''

          this.$emit("setName", this.names)
        }
      },
      openModal () {
        if (!this.viewCode) {
          this.messageUtil.warning(this.$t('m.eform.formDesign.label.qing-xian-pei-zhi-ye-mian-bian-ma'))
          return
        }
        if (!this.labelField) {
          this.messageUtil.warning(this.$t('m.eform.formDesign.label.qing-xian-pei-zhi-xian-shi-zi-duan'))
          return
        }

        let parameterValue = [];
        if(this.parameterConfig && (this.form || this.record)){
          let success = true;
          parameterValue = this.parameterConfig.map(item => {
            let value = null;
            if (item.outKey) {
              if(this.record && this.record.hasOwnProperty(item.outKey)){
                value = this.record[item.outKey]
              }else if(this.form){
                value = this.form.getFieldValue(item.outKey)
              }
            }
            if (!value && item.defaultValue) {
              value = item.defaultValue
            }
            if (!value && item.isRequired) {
              this.messageUtil.warning(item.customMessage || this.$t('m.eform.formDesign.label.Not_allowed_to_be_empty', [item.parameterKey]))
              success = false
            }
            return {
              colCode: item.parameterKey,
              queryValue: value
            }
          })
          if (!success) {
            return
          }
        }

        this.$refs.modal.show(parameterValue)
      },
      handleOK (rows) {
        let value = ''
        if (rows && rows.length > 0) {
          value = rows.map(row => row[this.keyField || this.labelField]).join(',')
        }

        if(this.fields && this.fields.length > 0){
          for(let i = 0; i < this.fields.length; i++){
            const item = this.fields[i];
            if(!item.from || !item.to){
              continue;
            }
            let toValue = ''
            if (rows && rows.length > 0) {
              toValue = rows.map(row => row[item.from]).join(',')
            }
            this.$emit('setFieldValue', item.to, toValue)
          }
        }

        this.$emit('change', value)
      },
      handleEmpty () {
        this.handleOK()
      }
    },
    model: {
      prop: 'value',
      event: 'change'
    }
  }
</script>

<style lang="less" scoped>
  .components-input-demo-presuffix .anticon-close-circle {
    cursor: pointer;
    color: #ccc;
    transition: color 0.3s;
    font-size: 12px;
  }

  .components-input-demo-presuffix .anticon-close-circle:hover {
    color: #f5222d;
  }

  .components-input-demo-presuffix .anticon-close-circle:active {
    color: #666;
  }
</style>
